<template>
  <CommonPage
    :scrollProps="{ onPulldown, pullupEnabled: false }"
    :loading="loading"
    custom-class="index-page"
  >
    <template #nav-left>
      <div class="index-page__title">
        <image src="@/assets/index/title.png" class="title-png" />
      </div>
    </template>
    <div class="index-page__wrapped">
      <div class="index-page__header">
        <CommonSearch
          type="button"
          class="skeleton-rect"
          @tap="onSearchFocus"
        />
        <image
          :src="avatar"
          class="user-png skeleton-radius"
          @tap="onNavigateUser"
        />
      </div>

      <div class="index-page__banner skeleton-rect">
        <nut-swiper :auto-play="3000" :loop="true">
          <nut-swiper-item v-for="(item, index) in bannerList" :key="index">
            <image
              src="@/assets/index/banner.png"
              @tap="onBannerLink(item.linkUrl)"
              class="index-page__banner-item"
            />
          </nut-swiper-item>
        </nut-swiper>
      </div>

      <div class="index-page__category skeleton-rect">
        <CategoryItem
          v-for="item in indexCategoryOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          :icon="item.icon"
          @tap="onAction(item.value)"
        />
      </div>

      <div class="index-page__task skeleton-rect">
        <IndexCard title="今日任务">
          <IndexTask :data="missionList" />
        </IndexCard>
      </div>

      <div class="index-page__well skeleton-rect">
        <IndexCard title="精选内容">
          <IndexWellContent :data="recomendList" @select="onRecomendSelect" />
        </IndexCard>
      </div>
    </div>
  </CommonPage>
</template>

<script lang="ts">
export default {
  name: "index-page",
};
</script>

<script setup lang="ts">
import { ref } from "vue";
import "./index.less";

import CommonPage from "@/components/common-page/index.vue";
import CategoryItem from "./components/category-item.vue";
import IndexCard from "./components/index-card.vue";
import IndexTask from "./components/index-task.vue";
import IndexWellContent from "./components/index-well-content.vue";
import CommonSearch from "@/components/common-search/index.vue";

import { indexCategoryOptions, IndexCategoryTypeEnum } from "./config";
import Taro, { useLoad } from "@tarojs/taro";
import { useLogin } from "@/hooks/useLogin";
import { ACCESS_TOKEN_CODE, ResponseCodeEnum } from "@/constants/index";
import {
  apiQueryBannerList,
  apiQueryMissionList,
  apiQueryRecommendTop,
  apiQuerySurveyList,
} from "@/apis/index";
import { CommonScrollProps } from "@/components/common-scroll/index.vue";
import { IMissionItemRes, ISurveyRes } from "@/apis/types/home";
import { useTabBarSelected } from "@/hooks/useTabBarSelected";
import { useUserInfo } from "@/hooks/useUserInfo";

const bannerList = ref<any[]>([]);
const missionList = ref<IMissionItemRes[]>([]);
const recomendList = ref<any[]>([]);
const surveyData = ref<ISurveyRes | null>();
const loading = ref(false);
const { setConmunityCode } = useLogin();
const { avatar } = useUserInfo();
const { setSelectIndex } = useTabBarSelected();

useLoad((param) => {
  const { code } = param;
  if (code) {
    setConmunityCode(code);
  } else {
    setConmunityCode("LnsWbz2mA8KU6raZMVK8");
  }

  loading.value = true;
  Promise.all([queryRecommendServer(), queryMissionList()]).finally(() => {
    loading.value = false;
  });
});

const onPulldown: CommonScrollProps["onPulldown"] = (done) => {
  Promise.all([queryRecommendServer(), queryMissionList()]).finally(() => {
    done();
  });
};

// const onPullup: CommonScrollProps["onPullup"] = async (done) => {
//   console.log("=== 上拉加载");
//   try {
//     await queryRecommendServer();
//   } catch (error) {
//   } finally {
//     done();
//   }
// };

const onSearchFocus = () => {
  Taro.navigateTo({ url: "/packageA/pages/index-search/index" });
};

const onAction = (type: string) => {
  switch (type) {
    case IndexCategoryTypeEnum.QA_SURVEY:
      navigateSurvey();
      break;
    case IndexCategoryTypeEnum.KNOWLEDGE_TESTING:
      navigateTesting();
      break;
    case IndexCategoryTypeEnum.HEALTH_KNOWLEDGE:
      Taro.switchTab({ url: "/pages/document/index" });
      setSelectIndex(1);

      break;
    case IndexCategoryTypeEnum.HEALTH_SCORE:
      Taro.switchTab({ url: "/pages/jifen/index" });
      setSelectIndex(2);
    default:
  }
};

const onNavigateUser = () => {
  Taro.switchTab({
    url: "/pages/persional/index",
  });
};
const navigateSurvey = () => {
  if (!surveyData.value) {
    Taro.showToast({ title: "获取问卷调查失败", icon: "error" });
    return;
  }

  Taro.navigateTo({
    url: `/packageA/pages/webview/index?title=问卷调查&url=${surveyData.value.survey}`,
  });
};

const navigateTesting = () => {
  if (!surveyData.value) {
    Taro.showToast({ title: "获取知识检测失败", icon: "error" });
    return;
  }

  Taro.navigateTo({
    url: `/packageA/pages/webview/index?title=知识检测&url=${surveyData.value.quiz}`,
  });
};

const onBannerLink = (url: string) => {
  if (!Taro.getStorageSync(ACCESS_TOKEN_CODE)) {
    Taro.navigateTo({ url: "/packageA/pages/login/index" });
  } else {
    Taro.navigateTo({
      url: `/packageA/pages/webview/index?title=活动&url=${decodeURIComponent(
        url
      )}`,
    });
  }
};

const onRecomendSelect = (id: string) => {
  if (!Taro.getStorageSync(ACCESS_TOKEN_CODE)) {
    Taro.navigateTo({ url: "/packageA/pages/login/index" });
  } else {
    Taro.navigateTo({
      url: `/packageA/pages/knowledge-detail/index?id=${id}`,
    });
  }
};

const queryBannerList = () => {
  return apiQueryBannerList().then((res) => {
    // console.log(res);
    bannerList.value = res.data;
  });
};

const queryMissionList = () => {
  return apiQueryMissionList().then((res) => {
    missionList.value = res.data;
  });
};

const queryRecommendServer = () => {
  return apiQueryRecommendTop().then((res) => {
    recomendList.value = [...recomendList.value, ...res.data];
  });
};

const querySurveyServer = () => {
  return apiQuerySurveyList().then((res: any) => {
    console.log();
    const { code, data } = res;
    if (code === ResponseCodeEnum.SUCCESS) {
      surveyData.value = data;
    }
  });
};
</script>
